function FXautoComplete(){
    this.Element = {
        minimumChar : 1,
        hasTabs : false,
        selectedCountryId : 0,
        hasDefaultText : true,
        googleSearchDefineId : ''
    };
}

FXautoComplete.prototype = {
    rowNumber     : 0,
    lastRowNumber : 1,
    searchText    : '',
    allowdReset   : true,
    allowdClosePopUp : true,
    allowdKeys : false,
    allowdForm : false,
    searchDeafaultVale : '',
    searchTimeOutRunning : false,
    arrowfocus:'',
    current_tab : 'All',
    previousTab : 'All',
    resultsData:'',
    firstRowId: 0,
    countriesData : undefined,
    countriesDefaultText : undefined,

    setTabsText : function(jsonTabs){
        var tabs = JSON.parse(jsonTabs);

        var c = '';
        var counter = 0;
        for(tab_id in tabs){
            var selected = (tabs[tab_id].selected == true) ? 'selected' : '';
            var first = (counter == 0) ? 'first' : '';
            var last = (counter == tabs.length - 1) ? 'last' : '';
            var country = (tabs[tab_id].id == 'search_box_topCountries') ? 'country' : '';

            if(tabs[tab_id].id == 'search_box_topCountries'){
                this.countriesDefaultText = tabs[tab_id].name;
            }

            c += '<li id="'+ tabs[tab_id].id +'" class="'+ first+' '+ last +' '+ country +' '+ selected +'"><a href="javascript:void(0);">'+ tabs[tab_id].name +'</a></li>';
            counter++;
        }
        $('#searchBoxTabsTopTabsTop').html(c);
    },
//General functions
    clearInputField : function(Obj) {

        if (searchSelfElement.searchDeafaultVale == ''){ ///set default value
            searchSelfElement.searchDeafaultVale = $(Obj).val();
        }
        if(searchSelfElement.searchDeafaultVale ==  $(Obj).val()){//check if need to clear
            $('#'+this.Element.searchTextInputId).val('');
            searchSelfElement.allowdReset = true;
            searchSelfElement.allowdKeys = false;
            searchSelfElement.allowdForm = false;
        }
    },

    markSelectedRow : function(){
        $('#'+this.Element.resultsInnerContainerId+' .row').removeClass('hoverSearch');
        $('#'+this.Element.mainResultRowIdPrefix+searchSelfElement.rowNumber).addClass('hoverSearch');

    },
    setSelectedRowNumber : function(row) {
        searchSelfElement.allowdForm = true;
        this.lastRowNumber = searchSelfElement.rowNumber;
        searchSelfElement.rowNumber = row;
    },
    changeCurrentTabDisplay : function(tabId){

        $('#'+this.Element.tabsPrefix+tabId).addClass('selected');
        $('#'+this.Element.tabsPrefix+tabId).siblings().each(function(){
            $(this).removeClass('selected');
        });
    },
    getSelectedRowElement : function(obj) {
        return $('#'+obj.Element.mainResultRowIdPrefix + searchSelfElement.rowNumber);
    },
    closeAutocomplete : function(obj){
        obj.Element.selectedCountryId = 0;
        searchSelfElement.previousTab = 'All';
        $('#'+this.Element.resultsInnerContainerId).scrollTop(0);
        $('#'+this.Element.countriesScrollDiv).scrollTop(0);
        $('#'+obj.Element.countriesWrapperId).addClass('displayNone');

        $('#'+obj.Element.tabsPrefix+'Countries').html('<a href="javascript:void(0);">'+ this.countriesDefaultText +'</a>');

        $('#'+obj.Element.resultsOuterContainerId).addClass('displayNone');
        $('#'+obj.Element.resultsInnerContainerId).html('');

    },
    closeSearchResultBox : function(){
        $('#'+this.Element.resultsOuterContainerId).addClass('displayNone');
        searchSelfElement.closeAutocomplete.call(this,this);

    },
    getResultsNumber : function(){
        return  $('#'+this.Element.resultsInnerContainerId).find("table tr").length;
    },
//End - General functions
//Key functionality
    keyCodeUp : function(){
        searchSelfElement.rowNumber--;
        var total_rows = searchSelfElement.getResultsNumber.call(this);
        if(searchSelfElement.rowNumber == -1 || isNaN(searchSelfElement.rowNumber) )
        {
            $('#'+this.Element.resultsInnerContainerId+' .row').removeClass('hoverSearch');
            $('#'+this.Element.formElementId).attr('onsubmit', 'return false;');
            searchSelfElement.arrowfocus = "text";
            $('#'+this.Element.searchTextInputId).focus();
            searchSelfElement.rowNumber = -1;
            $('#'+this.Element.searchTextInputId).val(searchSelfElement.searchText);
            searchSelfElement.allowdKeys = true;
        }
        if( (total_rows - searchSelfElement.rowNumber) >7){
            $('#'+this.Element.resultsInnerContainerId).scrollTop(($('#'+this.Element.resultsInnerContainerId).scrollTop())-22 );//22 is row height
        }

    },
    keyCodeDown : function(){

        if(searchSelfElement.rowNumber === undefined)
            searchSelfElement.rowNumber = 0;

        searchSelfElement.arrowfocus = "tabs";
        var total_rows = searchSelfElement.getResultsNumber.call(this);
        if(total_rows == searchSelfElement.rowNumber)
        {
            return;
        }

        $('#'+this.Element.formElementId).attr('onsubmit', 'return true;');
        searchSelfElement.rowNumber++;
        if(searchSelfElement.rowNumber > 7)
            $('#'+this.Element.resultsInnerContainerId).scrollTop(($('#'+this.Element.resultsInnerContainerId).scrollTop())+22 );//22 is row height
        else
            $('#'+this.Element.resultsInnerContainerId).scrollTop(0);
    },
    keyFunctunality : function(evt, keyCode){

        searchSelfElement.allowdForm = false;
        searchSelfElement.lastRowNumber = searchSelfElement.rowNumber;
        var showSymbol = true;
        if (keyCode == 40){ // down
            searchSelfElement.keyCodeDown.call(this);
        }
        else if (keyCode == 38){ //up
            searchSelfElement.keyCodeUp.call(this);
        }
        else if(keyCode == 39 && searchSelfElement.arrowfocus == "tabs" && (this.Element.hasTabs))//arrow right
        {
            var tab = searchSelfElement.getTheNextTab.call(this,1);//send the side (1 = right)
            if(tab == ''){
                showSymbol = false;
            }
            else{
                searchSelfElement.rowNumber = 0;
            }
            searchSelfElement.ChangeTabOnClick.call(this,tab);
        }
        else if(keyCode == 37 && searchSelfElement.arrowfocus == "tabs" && (this.Element.hasTabs))//arrow left
        {
            var tab = searchSelfElement.getTheNextTab.call(this,0);//send the side (2 = left)
            if(tab == ''){
                showSymbol = false;
            }else{
                searchSelfElement.rowNumber = 0;
            }
            searchSelfElement.ChangeTabOnClick.call(this,tab);
        }

        var selectedRow = searchSelfElement.getSelectedRowElement(this);
        if(selectedRow.length > 0 && showSymbol){
            var symbol = searchSelfElement.executeGetSymbol.call(this,selectedRow);
            searchSelfElement.symbolAndAction.call(this,symbol, selectedRow,$('#'+this.Element.searchTextInputId),false);
            searchSelfElement.markSelectedRow.call(this);
        }


    },
    setGoogleLink : function(){
        var googleSearchDefine = this.Element.googleSearchDefineId;
        var link ='/'+googleSearchDefine+'?q='+searchSelfElement.searchText;
        $('#'+this.Element.googleLinkID).attr('href', link);
        $('#'+this.Element.googleLinkID).html(searchSelfElement.searchText);
    },
    symbolAndAction : function(symbol, selectedRow, Obj,hover) {

        symbol = symbol.replace(/<\/\i>/g, "");
        symbol = symbol.replace(/<i class="bold">/g, "");
        symbol = symbol.replace(/<\/\I>/g, "");
        symbol = symbol.replace(/<I class=bold>/g, "");
        symbol = symbol.replace(/<\/\i>/g, "");
        symbol = symbol.replace(/<\/\i>/g, "");

        if(hover != true)
            $(Obj).val(symbol);
        if(this.Element.formElementId != undefined && this.Element.formElementId != '') {
            $('#'+this.Element.formElementId).attr('action', $('#' + selectedRow.attr('id') + ' .symbolName').attr('link'));
        }
    },
//End - Key functionality

//Show results and rows action
    displayAndSetSearchResultBox : function(){

        searchSelfElement.allowdForm = true;
        searchSelfElement.arrowfocus = 'tabs';

        if(searchSelfElement.firstRowId === 'no_results' && this.Element.googleSearchDefineId != ''){
            searchSelfElement.allowdForm = true;
            var googleSearchDefine = this.Element.googleSearchDefineId;
            $('#'+this.Element.formElementId).attr('action', '/'+googleSearchDefine+'?q='+searchSelfElement.searchText);
            $('#'+this.Element.formElementId).attr('onsubmit', 'return true;');
        }
        else if(searchSelfElement.firstRowId === 'no_results'){
            searchSelfElement.allowdForm = false;
            $('#'+this.Element.formElementId).attr('onsubmit', 'return false;');
        }
        else{
            $('#'+this.Element.formElementId).attr('onsubmit', 'return searchSelfElement.allowdForm;');
        }
        $('#'+this.Element.formElementId).attr('action', $('#'+this.Element.mainResultRowIdPrefix + searchSelfElement.firstRowId + ' .symbolName').attr('link'));
        var obj = this;
        if(this.Element.hasTabs)
            searchSelfElement.bindTabs.call(obj);

        searchSelfElement.executeBindResults.call(obj);
        $('#'+this.Element.resultsOuterContainerId).removeClass('displayNone');
    },

//End - Show results and rows action

//Send ajax call
    validateForSearch : function(evt,Obj) {
        if(evt.keyCode != 38 && evt.keyCode != 40 && evt.keyCode != 37 && evt.keyCode != 39) {
            searchSelfElement.searchText = $(Obj).val();
        }
        if((searchSelfElement.searchText.length > 0) && (evt.keyCode == 38 || evt.keyCode == 40 || evt.keyCode == 37 || evt.keyCode == 39) && searchSelfElement.allowdKeys)
        {
            searchSelfElement.keyFunctunality.call(this,evt,evt.keyCode);
        }
        else if((evt.keyCode != 13) && (searchSelfElement.searchText.length >= this.Element.minimumChar) && (!searchSelfElement.searchTimeOutRunning))
        {
            searchSelfElement.allowdReset = false;
            searchSelfElement.checkIfTimedOut.call(this);
        }
        else if(searchSelfElement.searchText.length == 0)
        {
            searchSelfElement.closeSearchResultBox.call(this);
        }
    },
    checkIfTimedOut : function(){

        if(!searchSelfElement.searchTimeOutRunning) {
            var that = this;
            searchSelfElement.searchTimeOutRunning = true;
            that.timer = setTimeout(function() { searchSelfElement.executeAutoCompleteSearch.call(that); },400);
        }
    },
    executeAutoCompleteSearch : function(){

        if(searchSelfElement.searchText == ''){
            searchSelfElement.searchTimeOutRunning = false;
            return;
        }

        var se = $('#'+ this.Element.formElementId +' > .searchGlassIcon');
        se.removeClass('searchGlassIcon newSiteIconsSprite');
        se.addClass('loading');

        var obj = this;
        searchSelfElement.allowdForm = false;
        if(obj.Element.selectedCountryId == '' || isNaN(parseInt(obj.Element.selectedCountryId)) )
            obj.Element.selectedCountryId = 0;
        if(obj.Element.googleSearchDefineId != ''){
            searchSelfElement.setGoogleLink.call(obj);
        }

        $.post(this.Element.url,
            {
                search_text    	  : searchSelfElement.searchText,
                term    	  : searchSelfElement.searchText,
                extraParameters   : searchSelfElement.extraParameters,
                country_id		  : obj.Element.selectedCountryId
            },
            function(data) {

                searchSelfElement.allowdKeys = false;
                searchSelfElement.allowdForm = false;
                searchSelfElement.resultsData = data;

                if(data != '' && data != null)
                {
                    searchSelfElement.allowdKeys = true;
                    searchSelfElement.arrowfocus = 'text';
                }
                else{
                    searchSelfElement.closeSearchResultBox.call(obj);
                    se.removeClass('loading');
                    se.addClass('searchGlassIcon newSiteIconsSprite');
                    return;
                }

                searchSelfElement.executeBuildResultsBox.call(obj);
                searchSelfElement.displayAndSetSearchResultBox.call(obj);

                se.removeClass('loading');
                se.addClass('searchGlassIcon newSiteIconsSprite');

            }, "json"
        );

        searchSelfElement.searchTimeOutRunning = false;
    },
//End - Send ajax call

//Default, bind searchText input field
    inputFieldBind : function(Obj){
        var that = this;

        Obj.bind(
            'focus' , function() {
                searchSelfElement.clearInputField.call(that, Obj);
                $('#'+ this.id + 'Container').addClass('topBarInputSelected');
                searchSelfElement.rowNumber = 0;
            });
        Obj.bind(
            'keyup' , function(event) {
                searchSelfElement.allowdKeys=true;
                searchSelfElement.validateForSearch.call(that, event, Obj);
            });
        $('#'+that.Element.searchTextInputId).bind(
            'focusout' , function() {
                $(document).click( function (evt) {
                    if(
                        ($(evt.target).parents('#'+that.Element.resultsInnerContainerId).length < 1)
                            &&
                            (evt.target.id != that.Element.resultsInnerContainerId )
                            &&
                            ($(evt.target).parents('#'+that.Element.searchTextInputId).length < 1)
                            &&
                            (evt.target.id != that.Element.searchTextInputId )
                            &&
                            ($(evt.target).parents('#'+that.Element.resultsOuterContainerId).length < 1)
                            &&
                            (evt.target.id != that.Element.resultsOuterContainerId )
                        ){
                        if( !(that.Element.hasDefaultText) )
                            $('#'+that.Element.searchTextInputId).val('');
                        else{
                            $('#'+that.Element.searchTextInputId).val(searchSelfElement.searchDeafaultVale);
                        }

                        $('#'+ that.Element.searchTextInputId + 'Container').removeClass('topBarInputSelected');
                        searchSelfElement.closeAutocomplete.call(that,that);
                    }
                });

            });


    },
//End - Default, bind searchText input field

//Tabs related functions
    //Coming here from clicking on tab or moving with arrows
    //tab_id is the tab to switch too
    ChangeTabOnClick : function (tab_id) {
        tab_id = tab_id.replace(this.Element.tabsPrefix,"");

        var obj = this;
        var changeTab = true;
        if(tab_id == ''){
            changeTab = false;
            tab_id = searchSelfElement.previousTab;
        }

        if(tab_id != 'Countries') {
            searchSelfElement.previousTab = tab_id;
            if(changeTab){
                searchSelfElement.executeBuildResultsBox.call(this);
            }
            searchSelfElement.displayAndSetSearchResultBox.call(this);

            if(searchSelfElement.arrowfocus != 'tabs'){
                $('#'+this.Element.formElementId).attr('onsubmit', 'return false;');
                searchSelfElement.arrowfocus = 'text';
            }
            if(changeTab){
                $('#'+this.Element.searchTextInputId).focus();
                setTimeout(function () {
                    $('#'+obj.Element.searchTextInputId).val(searchSelfElement.searchText);
                }, 1);
            }
        }
        else if(tab_id == 'Countries')
        {
            if($('#'+obj.Element.countriesWrapperId).hasClass('displayNone')){

                if(FXautoComplete.countriesData == undefined){
                    $.ajax({
                        url: "/search/countries",
                        dataType: "json",
                        async:   false,
                        success: function(data) {
                            FXautoComplete.countriesData = data;
                            var countries_c = '';
                            for (var i in data) {
                                var selected = data[i].selected == 'true' ? 'selected' : '';
                                countries_c += '';
                                countries_c +='<tr id="country_'+ data[i].country_id +'">';
                                countries_c +='<td class="'+ selected +'" id="tdCountry_'+ data[i].country_id +'">'+ data[i].country_name +'</td>';
                                countries_c +='</tr>';
                            }

                            $('#'+obj.Element.countriesTableId+' > tbody').html(countries_c);

                        }
                    });
                }

                searchSelfElement.bindCountries.call(this);
                $('#'+obj.Element.countriesWrapperId).removeClass('displayNone');
            }else{
                $('#'+obj.Element.countriesWrapperId).addClass('displayNone');
            }

        }

    },
    bindCountries : function(){
        var obj = this;
        $('#'+obj.Element.countriesTableId+' '+obj.Element.countriesType).each(function(){
            if(obj.Element.countryRowPrefix+obj.Element.selectedCountryId != this.id)
                $(this).removeClass('selected');
            $(this).unbind();

            $(this).click( function(){
                searchSelfElement.searchInCountryId.call(obj,this.id);
            });
        });
    },
    //called from onClick of countries
    searchInCountryId : function(tdId){

        $('#'+tdId).addClass('selected');
        this.Element.selectedCountryId = tdId.replace(this.Element.countryRowPrefix,'');

        searchSelfElement.allowdReset = false;
        $('#'+this.Element.countriesScrollDiv).scrollTop(0);
        $('#'+this.Element.countriesWrapperId).addClass('displayNone');
        searchSelfElement.checkIfTimedOut.call(this);
        $('#'+this.Element.tabsPrefix+'Countries').html('<a href="javascript:void(0);">'+$('#'+tdId).html()+'</a>');

        $('#'+this.Element.searchTextInputId).focus();
        setTimeout(function () {
            $('#'+this.Element.searchTextInputId).val(searchSelfElement.searchText);
        }, 1);

    },
    bindTabs : function(){
        var obj = this;
        $('#'+obj.Element.tabsDivId+' '+obj.Element.tabsType).each(function(){
            $(this).unbind();
            $(this).click( function(){
                searchSelfElement.ChangeTabOnClick.call(obj,this.id);
            })
        });
    },
    //get the side (1 = right , 2 = left)
    getTheNextTab :  function (side)
    {
        if($('#'+this.Element.hiddenDocDirectionId).attr('rel') == 'rtl')
        {
            if(side == 0)
                side = 1;
            else
                side = 0;
        }
        var obj = this;
        var tabsArr = new Array();
        var tabId = '';
        var tabNameClean = '';
        var index = 0;

        $('#'+obj.Element.tabsDivId+' '+obj.Element.tabsType).each(function(){

            tabId = this.id;
            tabNameClean = tabId.replace(obj.Element.tabsPrefix , '');
            tabsArr[index] = tabNameClean;
            index++;

        });
        var nextTab = '';
        for(var i=0;i<tabsArr.length;i++){
            if(searchSelfElement.previousTab == tabsArr[i])
            {
                if(side == 0)
                    side = -1;
                nextTab = tabsArr[i+side];
            }
        }
        if(nextTab != '' && nextTab != undefined && nextTab != 'Countries')
            nextTab = obj.Element.tabsPrefix+nextTab;
        else{
            nextTab = '';
        }
        return nextTab;

    },
//End - tabs related functions

//Execute specific search functions
    executeBuildResultsBox : function(){
        var obj = this;
        var data = searchSelfElement.resultsData;
        obj.buildSearchResults(data);
    },
    executeBindResults : function(){
        var obj = this;
        $('#'+obj.Element.resultsInnerContainerId+' .row').each(function(){
            $(this).unbind();
            obj.bindResults(this);
        });
    },
    executeGetSymbol : function(selectedRowObj){
        return (this.getSymbol(selectedRowObj));
    }
//End - Execute specific search functions


};

var searchSelfElement = FXautoComplete.prototype;


